package com.canbot.u05.activity.reception;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.canbot.u05.R;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.glide.GlideApp;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;

/**
 * 迎宾模式选择音底图面
 */
public class ReceptionModeChoosePicActivity extends ReceptionBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

        private String[] picPaths;

        private boolean[] bs;

        private int currentPosition;

        private ToastTools toastTools;

        private String picPath;


        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_reception_mode_choose_pic);
                initView();
                initData();
        }

        private void initData() {
                currentPosition = -1;
                String url = IpMsgConst.HTTP_URL_CHEST + "getAllPic";
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("path", "/uupic");
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                JsonResponse jsonResponse = new Gson().fromJson(result, JsonResponse.class);
                                if (jsonResponse != null) {
                                        if (jsonResponse.getRc() == -1) {
                                                toastTools.showText(getString(R.string.request_parameter_error));
                                                return;
                                        }
                                        Type type = new TypeToken<String[]>() {
                                        }.getType();
                                        picPaths = new Gson().fromJson(jsonResponse.getResult().toString(), type);
                                        if (picPaths == null || picPaths.length == 0) {
                                                toastTools.showText(getString(R.string.no_optional_background));
                                                return;
                                        }
                                        bs = new boolean[picPaths.length];
                                        if (!TextUtils.isEmpty(picPath)) {
                                                currentPosition = -1;
                                                for (int i = 0; i < picPaths.length; i++) {
                                                        if (picPath.contains(picPaths[i])) {
                                                                currentPosition = i;
                                                                break;
                                                        }
                                                }
                                                if (currentPosition != -1) {
                                                        bs[currentPosition] = true;
                                                }
                                        }

                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        if (dialogLoading != null){
                                                                LoadingDialogUtils.closeDialog(dialogLoading);
                                                        }
                                                        myBaseAdapter.notifyDataSetChanged();
                                                }
                                        });

                                }
                                else {
                                        toastTools.showText(getString(R.string.network_error));
                                }
                        }

                        @Override
                        public void onFailure() {
                                if (dialogLoading != null){
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                }
                                toastTools.showText(getString(R.string.network_error));
                        }
                });
        }

        private void initView() {
                toastTools = ToastTools.newInstance(this);
                ((TextView) findViewById(R.id.textView_title)).setText("选择底图");
                findViewById(R.id.iv_usher_mode_choose_pic_cancel).setOnClickListener(this);
                findViewById(R.id.imageView_back).setOnClickListener(this);
                findViewById(R.id.iv_usher_mode_choose_pic_sure).setOnClickListener(this);
                GridView gridView = (GridView) findViewById(R.id.usher_mode_choose_pic_gv);
                gridView.setAdapter(myBaseAdapter);
                gridView.setOnItemClickListener(this);
                picPath = getIntent().getStringExtra("picPath");
        }
        private Dialog dialogLoading;
        @Override
        public void onClick(View v) {
                switch (v.getId()) {
                        case R.id.iv_usher_mode_choose_pic_cancel:
                                finish();
                                break;
                        case R.id.iv_usher_mode_choose_pic_sure:
                                if (currentPosition == -1) {
                                        toastTools.showText(getString(R.string.select_base_map));
                                        return;
                                }
                                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                                updatePic(picPaths[currentPosition]);
                                break;
                        case R.id.imageView_back:
                                finish();
                                break;
                }

        }

        private void updatePic(final String filePath) {
                String url = IpMsgConst.HTTP_URL_CHEST + "usherModeAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", 0);
                hashMap.put("usherPic", filePath);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                toastTools.showText(getString(R.string.upload_complete));
                                Intent intent = new Intent();
                                intent.putExtra("picPath", filePath);
                                setResult(RESULT_OK, intent);
                                finish();
                        }

                        @Override
                        public void onFailure() {
                                toastTools.showText(getString(R.string.service_error_hint));
                                LoadingDialogUtils.closeDialog(dialogLoading);
                        }
                });
        }


        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("test", "onItemClick" + position);
                if (currentPosition != -1) {
                        bs[currentPosition] = false;
                }
                currentPosition = position;
                bs[position] = true;
                myBaseAdapter.notifyDataSetChanged();
        }

        BaseAdapter myBaseAdapter = new BaseAdapter() {
                @Override
                public int getCount() {
                        return picPaths == null ? 0 : picPaths.length;
                }

                @Override
                public Object getItem(int position) {
                        return position;
                }

                @Override
                public long getItemId(int position) {
                        return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        if (convertView == null) {
                                LayoutInflater inflater = LayoutInflater.from(ReceptionModeChoosePicActivity.this);
                                convertView = inflater.inflate(R.layout.usher_choose_pic_item, parent, false);
                                Holder holder = new Holder(convertView);
                                convertView.setTag(holder);
                        }
                        Holder holder = ((Holder) convertView.getTag());
                        holder.setData(position);
                        return convertView;
                }
        };

        class Holder {

                private final TextView textView;

                private final Button checkButton;

                private final ImageView imageView;

                public Holder(View inflate) {
                        textView = (TextView) inflate.findViewById(R.id.tv);
                        checkButton = (Button) inflate.findViewById(R.id.cb);
                        imageView = (ImageView) inflate.findViewById(R.id.iv);
                }

                public void setData(int position) {
                        if (picPaths[position].contains("/uupic/")) {
                                textView.setText(picPaths[position].replace("/uupic/", ""));
                        }
                        checkButton.setSelected(bs[position]);
                        checkButton.setTag(position);
                        checkButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                        int tag = (Integer) checkButton.getTag();
                                        if (currentPosition == tag && bs[currentPosition]) {
                                                bs[currentPosition] = false;
                                                currentPosition = -1;
                                                myBaseAdapter.notifyDataSetChanged();
                                                return;
                                        }
                                        if (currentPosition != -1) {
                                                bs[currentPosition] = false;
                                        }
                                        currentPosition = tag;
                                        bs[currentPosition] = true;
                                        myBaseAdapter.notifyDataSetChanged();
                                }
                        });
                        GlideApp.with(ReceptionModeChoosePicActivity.this).clear(imageView);
                        GlideApp.with(ReceptionModeChoosePicActivity.this)
                                .asDrawable()
                                .load(IpMsgConst.HTTP_URL_CHEST + picPaths[position].replace("/uupic/","/uupic_thumb/"))
                                .thumbnail(0.1f)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                                .skipMemoryCache(false)
                                .placeholder(R.drawable.sales_banner01)//占位图
                                .error(R.drawable.ic_launcher)
                                .override(100, 100)
                                .into(imageView);
                }
        }
}
